﻿using AutoMapper;
using PagedList;
using SIG.Infrastructure.Configs;
using SIG.Infrastructure.Helper;
using SIG.InputModel.Admin.Teams;
using SIG.Model;
using SIG.Model.Enums;
using SIG.Service;
using SIG.ViewModel;
using SIG.ViewModel.Admin.Teams;
using SIG.WebMVC.Filters;
using System;
using System.Collections.Generic;
using System.Web.Mvc;
using SIG.Model.Teams;
using System.Xml.Linq;
using System.Linq;
using SIG.Resources.Admin;

namespace SIG.WebMVC.Areas.Admin.Controllers
{
    [SIGAuth]
    public class TeamController : BaseController
    {
        private readonly ITeamService _teamService;
        private readonly IPageMetaService _pageMetaService;
        private readonly IMapper _mapper;

        public TeamController(ITeamService teamService, IPageMetaService pageMetaService, IMapper mapper)
        {
            _teamService = teamService;
            _pageMetaService = pageMetaService;
            _mapper = mapper;

        }
        // GET: Admin/Team

        #region Team

        public ActionResult Index(int? page, string keyword)
        {
            TeamListVM teamListVM = GetElements(page, keyword);
         
            ViewBag.PageSizes = new SelectList(Site.PageSizes());
            return View(teamListVM);

        }

        private TeamListVM GetElements(int? page, string keyword)
        {
            var teamListVM = new TeamListVM();

            teamListVM.Keyword = keyword;
            teamListVM.PageIndex = (page ?? 1) - 1;
            teamListVM.PageSize = SettingsManager.Team.PageSize;
            int totalCount;
            var teamlist = _teamService.GetPagedElements(teamListVM.PageIndex, teamListVM.PageSize, teamListVM.Keyword, out totalCount);
            var teamVMList = _mapper.Map<List<Team>, List<TeamVM>>(teamlist);
            teamListVM.TotalCount = totalCount;
            teamListVM.Teams = new StaticPagedList<TeamVM>(teamVMList, teamListVM.PageIndex + 1, teamListVM.PageSize, teamListVM.TotalCount); ;
            return teamListVM;
        }


        [HttpPost]
        public JsonResult PageSizeSet(int pageSize)
        {
            try
            {
                var xmlFile = Server.MapPath("~/Config/TeamSettings.config");
                XDocument doc = XDocument.Load(xmlFile);

                var item = doc.Descendants("Settings").FirstOrDefault();
                item.Element("PageSize").SetValue(pageSize);
                doc.Save(xmlFile);

                return Json(AR, JsonRequestBehavior.DenyGet);
            }
            catch (Exception ex)
            {
                AR.Setfailure(ex.Message);
                return Json(AR, JsonRequestBehavior.DenyGet);
            }
        }


        [HttpGet]
        public ActionResult Add()
        {
            var vTeam = new TeamIM();
            vTeam.Active = true;
          

            return PartialView("_Add", vTeam);
        }



        [HttpPost]
        public JsonResult Add(TeamIM vm)
        {

            if (!ModelState.IsValid)
            {
                AR.Setfailure(GetModelErrorMessage());
                return Json(AR, JsonRequestBehavior.DenyGet);
            }

            var team = _mapper.Map<TeamIM, Team>(vm);
            _teamService.Create(team);

            if (!string.IsNullOrEmpty(vm.Keywords) || !string.IsNullOrEmpty(vm.SEODescription))
            {
                var pageMeta = new PageMeta()
                {
                    ObjectId = team.Id,
                    Keyword = vm.Keywords.Replace('，', ','),
                    Description = vm.SEODescription,
                    ModelType = ModelType.JOB
                };
                _pageMetaService.Create(pageMeta);
            }

            int count;
            int pageSize = SettingsManager.Team.PageSize;
            var list = _teamService.GetPagedElements(0, pageSize, string.Empty,out count);
            List<TeamVM> teamList = _mapper.Map<List<Team>, List<TeamVM>>(list);
            AR.Data = RenderPartialViewToString("_TeamList", teamList);

            AR.SetSuccess(String.Format(Messages.AlertCreateSuccess, EntityNames.Team));
            return Json(AR, JsonRequestBehavior.DenyGet);

        }


        [HttpGet]
        public ActionResult Edit(int id)
        {

            Team team = _teamService.GetById(id);
            if (team == null)
            {
                AR.Setfailure(Messages.HttpNotFound);
                return Json(AR, JsonRequestBehavior.AllowGet);
            }

            var vm = _mapper.Map<TeamIM>(team);
           

            return PartialView("_Edit", vm);
        }

        [HttpPost]
        [ValidateAntiForgeryToken]

        public JsonResult Edit(TeamIM vm)
        {

            if (!ModelState.IsValid)
            {
                AR.Setfailure(GetModelErrorMessage());
                return Json(AR, JsonRequestBehavior.DenyGet);
            }

        
            var team = _mapper.Map<TeamIM, Team>(vm);
            _teamService.Update(team);

            var pageMeta = _pageMetaService.GetPageMeta(ModelType.JOB, vm.Id);
            pageMeta = pageMeta ?? new PageMeta();

            if (!string.IsNullOrEmpty(vm.Keywords) || !string.IsNullOrEmpty(vm.Description))
            {

                pageMeta.ObjectId = vm.Id;
                pageMeta.Keyword = vm.Keywords;
                pageMeta.Description = vm.Description;
                pageMeta.ModelType = ModelType.JOB;

                if (pageMeta.Id > 0)
                {
                    _pageMetaService.Update(pageMeta);
                }
                else
                {
                    _pageMetaService.Create(pageMeta);
                }
            }


            var teamVM = _mapper.Map<TeamVM>(team);

            AR.Id = team.Id;
            AR.Data = RenderPartialViewToString("_TeamItem", teamVM);

            AR.SetSuccess(String.Format(Messages.AlertUpdateSuccess, EntityNames.Team));
            return Json(AR, JsonRequestBehavior.DenyGet);

        }

        // DELETE: /User/DeleteSite
        [HttpPost]
        [ValidateAntiForgeryToken]
        public JsonResult Delete(int id)
        {

            Team vTeam = _teamService.GetById(id);
                     

            _teamService.Delete(vTeam);
            AR.SetSuccess(String.Format(Messages.AlertDeleteSuccess, EntityNames.Team));
            return Json(AR, JsonRequestBehavior.DenyGet);

        }


        [HttpPost]
        [ValidateAntiForgeryToken]
        public JsonResult IsActive(int id)
        {

            var vTeam = _teamService.GetById(id);
            if (vTeam == null)
            {
                AR.Setfailure(Messages.HttpNotFound);
                return Json(AR, JsonRequestBehavior.DenyGet);
            }

            try
            {
                vTeam.Active = !vTeam.Active;
                _teamService.Update(vTeam);
                var vm = _mapper.Map<TeamVM>(vTeam);

                AR.Data = RenderPartialViewToString("_TeamItem", vm);
                AR.SetSuccess(String.Format(Messages.AlertUpdateSuccess, EntityNames.Team));
                return Json(AR, JsonRequestBehavior.DenyGet);
            }
            catch (Exception ex)
            {
                AR.Setfailure(ex.Message);
                return Json(AR, JsonRequestBehavior.DenyGet);
            }
        }

        
        


        #endregion
    }
}